import java.util.Deque;
import java.util.LinkedList;

public class Solution224 {
    public int calculate(String s) {
        Deque<Integer> nums = new LinkedList<>();
        Deque<Character> operators = new LinkedList<>();
        char[] chars = s.toCharArray();
        int j = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ' ') {
                chars[j++] = chars[i];
            }
        }
        s = new String(chars).substring(0, j);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                if (i == 0 || s.charAt(i - 1) < '0' || s.charAt(i - 1) > '9') {
                    nums.push(c - '0');
                } else {
                    nums.push(nums.poll() * 10 + (c - '0'));
                }
            } else if (c == '+' || c == '-') {
                if (i == 0 || s.charAt(i - 1) == '(') {
                    nums.push(0);
                } else if (!operators.isEmpty()) {
                    char pre = operators.peek();
                    if (pre == '+' || pre == '-') {
                        nums.push(calculate(nums.poll(), nums.poll(), operators.poll()));
                    }
                }
                operators.push(c);
            } else if (c == '(') {
                operators.push(c);
            } else if (c == ')') {
                while (!operators.isEmpty() && operators.peek() != '(') {
                    nums.push(calculate(nums.poll(), nums.poll(), operators.poll()));
                }
                operators.poll();
            }
        }
        if (operators.isEmpty()) {
            return nums.peek();
        }
        return calculate(nums.poll(), nums.poll(), operators.poll());
    }

    int calculate(Integer b, Integer a, Character o) {
        if (o == '+') {
            return a + b;
        } else {
            return a - b;
        }
    }
}
